#include <p18f4550.h>         
#include <delays.h>           
#include <xlcd.h>
#include <stdio.h>

/*-------------------------------------------------------
OpenLCD() redirects stdout (standard out) to the LCD.
Therefore, printf() can be used to write tot the LCD

Connections:

LCD			PIC
----------------
1			GND
2			VDD
3			GND
4			B7
5			B6
6			B4
7			Not connected
8			Not connected
9			Not connected
10			Not connected
11			B0
12			B1
13			B2
14			B3
(15)		LCD backlight, not necessary
(16)		LCD backlight, not necessary

-------------------------------------------------------*/
// Set cursor at start of line 1
void LcdSetLine1(void){
	while(BusyXLCD()); 
	SetDDRamAddr(0);	// set address 
}

// Set cursor at start of line 2
void LcdSetLine2(void){
	while(BusyXLCD()); 
	SetDDRamAddr(0x40);	// set address 
}

// Clear LCD display
void LcdClear(void)
{
	WriteCmdXLCD(0x01);
}

// Open LCD module
void LcdOpen(void)
{
	OpenXLCD( FOUR_BIT & LINES_5X7 ); 
	while(BusyXLCD()); 
	WriteCmdXLCD(BLINK_OFF & CURSOR_OFF );  
	while(BusyXLCD()); 	
	LcdClear();
	
	stdout = _H_USER; // redirect printf to LCD using _user_putc
	//stdout = _H_USART; // use this redirect stdout back to usart if desired
}

// Close LCD module
void LcdClose(void)
{
	LcdClear();
}

//========================PrintfRedirection===============================
// _user_putc is called by printf if stdout is set to _H_USER.
int _user_putc(char data){
    while(BusyXLCD()); 
	putcXLCD(data); // write character to LCD display
}

// =====================Delay functions for LCD===========================

// Delay for 18 clockcycles
void DelayFor18TCY( void )
{
	Delay10TCYx(1);
	Delay1TCY();
	Delay1TCY();
}

// Delay 1  x * millisecond
void Delay1mSLCD(int x)
{
	int i;
	// Cycles = (TimeDelay * Fosc) / 4
	// Cycles = (1ms * 48MHz) / 4
	// Cycles = 12,000

	for (i=0; i<x;i++) Delay1KTCYx(12);
}

// Delay for 15 milliseconds
void DelayPORXLCD (void)
{
	Delay1mSLCD(15);	// Delay of 15ms
	return;
}

// Delay for 5 milliseconds
void DelayXLCD (void)
{
	Delay1mSLCD(5);	// Delay of 5ms
	return;
}
